export default {
  namespaced: true,
  state: {
    goodsList: uni.getStorageSync('cart') || [] // 购物车中的商品列表
  },
  mutations: {
    addtoCart (state, goods) {
      // console.log('cart', goods)
      const findGoods = state.goodsList.find(
        // item = 本身的值 goods=新增的值
        item => item.goods_id === goods.goods_id
      )
      // 如果商品存在数量累加
      if (findGoods) {
        findGoods.goods_number += goods.goods_number
      } else {
        // 不存在 push
        state.goodsList.push(goods)
      }
      // 最后保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 更改商品的状态
    updataGoodsState (state, goods) {
      const findGoods = state.goodsList.find(
        // item = 本身的值 goods=新增的值
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        findGoods.goods_state = goods.goods_state
      }
      // 最后保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 更改商品的数量
    updataGoodsNumber (state, goods) {
      const findGoods = state.goodsList.find(
        // item = 本身的值 goods=新增的值
        item => item.goods_id === goods.goods_id
      )
      if (findGoods) {
        findGoods.goods_number = goods.goods_number
      }
      // 最后保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 根据id删除商品
    deleteGoodsById (state, goods_id) {
      // 过滤不要的数据
      state.goodsList = state.goodsList.filter(
        item => item.goods_id !== goods_id
      )
      // 最后保存到本地
      uni.setStorageSync('cart', state.goodsList)
    },
    // 更改所有商品的状态
    updateAllGoodsState (state, goods_state) {
      state.goodsList.forEach(item => {
        item.goods_state = goods_state
      })

      // 最后保存到本地
      uni.setStorageSync('cart', state.goodsList)
    }
  },
  getters: {
    // 获取仓库中商品总数
    getTotal (state) {
      let total = 0
      state.goodsList.forEach(item => {
        total += item.goods_number
      })
      return total
    },
    getgoodsList (state) {
      return state.goodsList
    },
    // 选中的数量
    getSelectedTotal (state) {
      let total = 0
      state.goodsList.forEach(item => {
        if (item.goods_state) {
          total += item.goods_number
        }
      })
      return total
    },
    // 选中的金额
    getSelectedAmount (state) {
      let amount = 0
      state.goodsList.forEach(item => {
        if (item.goods_state) {
          amount += item.goods_number * item.goods_price
        }
      })
      return amount.toFixed(2)
    }
  }
}
